<template>
  <!-- Rename root class -->
  <div class="universal-node-details" v-if="nodeData">
    <el-descriptions title="Node Information" :column="1" border size="small">
      <!-- CORRECTED: Use nodeId prop -->
      <el-descriptions-item label="Node ID">{{ nodeId || 'N/A' }}</el-descriptions-item>
      <el-descriptions-item label="Node Name">{{ nodeData.name || '[Unnamed]' }}</el-descriptions-item>
      <el-descriptions-item label="Semantic Type">
        <el-tag size="small" :color="semanticTypeColor">{{ nodeData.nodeSemanticType }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="Source Format">
        <el-tag size="small" :color="sourceFormatColor">{{ nodeData.format }}</el-tag> <!-- Use nodeData.format -->
      </el-descriptions-item>
      <!-- ADD Path Display -->
      <el-descriptions-item label="Path">{{ nodeData.path || 'N/A' }}</el-descriptions-item>
      <el-descriptions-item label="Level">{{ nodeData.level ?? 'N/A' }}</el-descriptions-item>
      <el-descriptions-item label="Order">{{ nodeData.order ?? 'N/A' }}</el-descriptions-item>
      <el-descriptions-item label="Children Count">{{ nodeData.childrenIds?.length || 0 }}</el-descriptions-item>
      <!-- ADDED: Children IDs List -->
      <el-descriptions-item label="Children IDs" v-if="nodeData.childrenIds && nodeData.childrenIds.length > 0">
        <div class="id-list">{{ nodeData.childrenIds.join(', ') }}</div>
      </el-descriptions-item>

    </el-descriptions>

    <!-- Evaluated Value Section (Handles 'evaluatedResult' type via computed prop) -->
    <el-descriptions
      v-if="evaluatedValue !== undefined && (nodeData.format === 'javascript' || nodeData.format === 'typescript')"
      :title="evaluatedValueTitle"
      :column="1"
      border
      size="small"
      class="section-margin"
    >
      <el-descriptions-item :label="evaluatedValueLabel">
        <RichValueDisplay :value="evaluatedValue" :path="nodeData.path ?? undefined" />
      </el-descriptions-item>
    </el-descriptions>

    <!-- Source Snippet Section -->
    <el-descriptions
      v-else-if="nodeData.nodeSemanticType === 'sourceSnippet'"
      title="Source Snippet"
      :column="1" border size="small" class="section-margin"
    >
      <el-descriptions-item label="Code">
        <!-- Assume the snippet is in nodeData.content for now -->
        <pre class="value-display">{{ nodeData.content || '[No Snippet Available]' }}</pre>
      </el-descriptions-item>
    </el-descriptions>

    <!-- Original Value Section -->
    <el-descriptions
      v-else-if="nodeData.nodeSemanticType === 'value'"
      title="Original Value"
      :column="1" border size="small" class="section-margin"
    >
      <el-descriptions-item label="Value">
        <pre class="value-display">{{ displayOriginalValue }}</pre>
      </el-descriptions-item>
    </el-descriptions>

    <!-- Comment Section -->
    <el-descriptions
      v-else-if="nodeData.nodeSemanticType === 'comment'"
      title="Comment"
      :column="1" border size="small" class="section-margin"
    >
      <el-descriptions-item label="Comment">
        <pre class="value-display">{{ formattedComment }}</pre>
      </el-descriptions-item>
    </el-descriptions>

    <!-- Fallback Content Section -->
    <el-descriptions
      v-else-if="nodeData.content"
      title="Content"
      :column="1" border size="small" class="section-margin"
    >
      <el-descriptions-item label="Content">
        <pre class="value-display">{{ nodeData.content }}</pre>
      </el-descriptions-item>
    </el-descriptions>

    <!-- FIXED Attributes Section -->
    <el-descriptions title="Attributes" :column="1" border size="small" v-if="hasAttributes" class="section-margin">
      <el-descriptions-item
          v-for="([attrName, attrValue]) in Object.entries(nodeData.attributes)"
          :key="attrName"
          :label="attrName"
      >
        {{ attrValue }}
      </el-descriptions-item>
    </el-descriptions>
    <el-empty description="No attributes" v-else-if="!hasAttributes && nodeData.nodeSemanticType !== 'value' && nodeData.nodeSemanticType !== 'comment'" class="section-margin"></el-empty> <!-- Show empty state only for relevant types -->

    <!-- Keep Metadata Section -->
    <el-descriptions title="Metadata" :column="1" border size="small" v-if="hasMetadata" class="section-margin">
      <!-- Common Comment -->
      <el-descriptions-item label="Comment" v-if="nodeData.metadata?.comment">
        <pre class="metadata-display">{{ formattedComment }}</pre>
      </el-descriptions-item>
      <!-- XML Metadata -->
      <template v-if="nodeData.metadata?.xml">
        <el-descriptions-item label="XML Namespace" v-if="nodeData.metadata.xml.namespace">
          {{ nodeData.metadata.xml.namespace }}
        </el-descriptions-item>
        <el-descriptions-item label="XML SelfClosing" v-if="nodeData.metadata.xml.isSelfClosing !== undefined">
          {{ nodeData.metadata.xml.isSelfClosing ? 'Yes' : 'No' }}
        </el-descriptions-item>
        <el-descriptions-item label="XML PI Target" v-if="nodeData.metadata.xml.processingInstruction?.target">
          {{ nodeData.metadata.xml.processingInstruction.target }}
        </el-descriptions-item>
        <el-descriptions-item label="XML PI Data" v-if="nodeData.metadata.xml.processingInstruction?.data">
          <pre class="metadata-display">{{ nodeData.metadata.xml.processingInstruction.data }}</pre>
        </el-descriptions-item>
      </template>
      <!-- YAML Metadata -->
      <template v-if="nodeData.metadata?.yaml">
        <el-descriptions-item label="YAML Tag" v-if="nodeData.metadata.yaml.tag">
          {{ nodeData.metadata.yaml.tag }}
        </el-descriptions-item>
        <el-descriptions-item label="YAML Anchor" v-if="nodeData.metadata.yaml.anchor">
          &amp;{{ nodeData.metadata.yaml.anchor }}
        </el-descriptions-item>
        <el-descriptions-item label="YAML isAlias" v-if="nodeData.metadata.yaml.isAlias !== undefined">
          {{ nodeData.metadata.yaml.isAlias ? 'Yes (*' + (nodeData.metadata.yaml.aliasTargetId || 'ref') + ')' : 'No' }}
        </el-descriptions-item>
      </template>
      <!-- TOML Metadata -->
      <template v-if="nodeData.metadata?.toml">
        <el-descriptions-item label="TOML isInlineTable" v-if="nodeData.metadata.toml.isInlineTable !== undefined">
          {{ nodeData.metadata.toml.isInlineTable ? 'Yes' : 'No' }}
        </el-descriptions-item>
      </template>
      <!-- Display other arbitrary metadata -->
      <template v-for="(value, key) in otherMetadata" :key="key">
        <el-descriptions-item :label="`Metadata: ${key}`">
          <!-- Use RichValueDisplay for metadata values too -->
          <RichValueDisplay :value="value" :path="`metadata.${key}`" />
        </el-descriptions-item>
      </template>
    </el-descriptions>

  </div>
  <div v-else>
    <el-empty description="No node data available" />
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
// Ensure correct type import
import type { UniversalFlowNodeData, SourceFormat, NodeSemanticType } from '@/models/universalFlow';
// Keep necessary Element Plus components
import { ElDescriptions, ElDescriptionsItem, ElTag, ElEmpty } from 'element-plus';
import { formatColorCodes, semanticTypeColorCodes } from '@/config';
import { useUniversalEditorStore } from '@/stores/universalEditorStore';
// --- REVERT TO ALIAS PATHS --- 
import RichValueDisplay from '@/components/misc/RichValueDisplay.vue'; // Reverted path
// --- IMPORT V2 Util --- 
import { getValueFromPath } from '@/utils/objectPathUtilsV2'; // Reverted path, USE V2

// Define Component Name (Optional but good practice)
// defineOptions({ name: 'UniversalNodeDetails' });

interface Props {
  // ADD nodeId prop
  nodeId: string | null | undefined;
  // Ensure prop type matches the expected data model
  nodeData: UniversalFlowNodeData | null | undefined;
}

const props = defineProps<Props>();
const editorStore = useUniversalEditorStore();

// Keep color computed properties
const sourceFormatColor = computed<string>(() => {
  const defaultColor = '#909399';
  if (!props.nodeData) return defaultColor;
  // Use format, not sourceFormat
  return formatColorCodes[props.nodeData.format] || defaultColor;
});

const semanticTypeColor = computed<string>(() => {
  const defaultColor = '#A0A0A0';
  if (!props.nodeData) return defaultColor;
  return semanticTypeColorCodes[props.nodeData.nodeSemanticType] || defaultColor;
});

// Keep displayValue computed property
const displayValue = computed(() => {
  if (!props.nodeData || !('value' in props.nodeData) || props.nodeData.value === undefined) {
    // Return empty string or specific text if value is not applicable/present
    return '';
  }
  const value = props.nodeData.value;
  if (value === null) return 'null';
  if (typeof value === 'boolean') return value ? 'true' : 'false';
  if (value instanceof Date) return value.toISOString();
  if (typeof value === 'object') return JSON.stringify(value); // Should not happen for 'value' type ideally
  return String(value);
});

// FIXED hasAttributes computed property
const hasAttributes = computed(() => {
  // Check if nodeData exists and attributes is an object with keys
  return !!props.nodeData && typeof props.nodeData.attributes === 'object' && Object.keys(props.nodeData.attributes).length > 0;
});

// Keep hasMetadata, formattedComment, otherMetadata computed properties
const hasMetadata = computed(() => {
  if (!props.nodeData?.metadata) return false;
  return Object.keys(props.nodeData.metadata).some(key =>
      ['comment', 'xml', 'yaml', 'toml'].includes(key)
          ? props.nodeData?.metadata?.[key] !== undefined && (typeof props.nodeData?.metadata?.[key] !== 'object' || Object.keys(props.nodeData?.metadata?.[key] ?? {}).length > 0)
          : props.nodeData?.metadata?.[key] !== undefined
  );
});
const formattedComment = computed(() => {
  if (!props.nodeData?.metadata?.comment) return '';
  return Array.isArray(props.nodeData.metadata.comment)
      ? props.nodeData.metadata.comment.join('\n')
      : props.nodeData.metadata.comment;
});
const otherMetadata = computed(() => {
  if (!props.nodeData?.metadata) return {};
  const knownKeys = ['comment', 'xml', 'yaml', 'toml'];
  const other: Record<string, any> = {};
  for (const key in props.nodeData.metadata) {
    if (!knownKeys.includes(key) && Object.prototype.hasOwnProperty.call(props.nodeData.metadata, key) && props.nodeData.metadata[key] !== undefined) {
      other[key] = props.nodeData.metadata[key];
    }
  }
  return other;
});

// --- Computed Property for Evaluated Value --- //
const evaluatedValue = computed(() => {
    // RE-ADD DEBUG LOGGING
    console.log("[UniversalNodeDetails] Computing evaluatedValue...");
    console.log("  > Node Path:", props.nodeData?.path);
    console.log("  > Semantic Type:", props.nodeData?.nodeSemanticType); // Log semantic type
    console.log("  > evaluatedConfig available:", !!editorStore.evaluatedConfig);

    if (!props.nodeData || (props.nodeData.format !== 'javascript' && props.nodeData.format !== 'typescript')) {
        console.log("[UniversalNodeDetails] evaluatedValue -> undefined (not JS/TS format)"); // RE-ADD Log
        return undefined; // Not applicable
    }
    // Check for execution error first (applies to all JS/TS)
    if (editorStore.evaluatedConfig?.__universalExecutionError__) {
        console.log("[UniversalNodeDetails] evaluatedValue -> returning execution error object"); // RE-ADD Log
        // Return the error itself to be displayed by RichValueDisplay
        return editorStore.evaluatedConfig.__universalExecutionError__;
    }

    // --- ADDED: Special handling for 'evaluatedResult' type ---
    if (props.nodeData.nodeSemanticType === 'evaluatedResult') {
        console.log("[UniversalNodeDetails] evaluatedValue -> returning full evaluatedConfig for 'evaluatedResult' type");
        return editorStore.evaluatedConfig; // Return the whole object
    }
    // --- END ADDED ---

    let valueAtPath;
    try {
        // --- Use V2 function --- 
        valueAtPath = getValueFromPath(editorStore.evaluatedConfig, props.nodeData.path);
        // -----------------------
        // RE-ADD DEBUG LOGGING
        console.log(`[UniversalNodeDetails] getValueFromPath('${props.nodeData.path}') ->`, valueAtPath);
        if (valueAtPath instanceof Error) {
            console.log(`[UniversalNodeDetails] Error object found. Has 'cause' property:`, 'cause' in valueAtPath, "Value of cause:", valueAtPath.cause);
        }
    } catch (e) {
        console.error(`[UniversalNodeDetails] Error calling getValueFromPath for path '${props.nodeData.path}':`, e);
        valueAtPath = undefined;
    }

    return valueAtPath;
});

// --- NEW: Computed titles/labels for the evaluated value section ---
const evaluatedValueTitle = computed(() => {
  if (props.nodeData?.nodeSemanticType === 'evaluatedResult') {
    return 'Evaluated Result (from QuickJS)';
  }
  return 'Evaluated Value (from QuickJS)';
});
const evaluatedValueLabel = computed(() => {
   if (props.nodeData?.nodeSemanticType === 'evaluatedResult') {
    return 'Result';
  }
  return 'Value';
});
// --- END NEW ---

// --- Computed Property for Original Value/Content/Comment (Fallback) --- //
const displayOriginalValue = computed(() => {
  if (!props.nodeData) return '';
  if (props.nodeData.nodeSemanticType === 'value') {
    const value = props.nodeData.value;
    if (value === null) return 'null';
    if (typeof value === 'boolean') return value ? 'true' : 'false';
    if (value instanceof Date) return value.toISOString(); // Show full ISO string in details
    if (typeof value === 'object') return JSON.stringify(value, null, 2); // Pretty print if it happens
    return String(value);
  }
  if (props.nodeData.nodeSemanticType === 'comment') {
    return formattedComment.value; // Use existing computed
  }
  if (props.nodeData.content) {
    return props.nodeData.content;
  }
  return '';
});

</script>

<style lang="scss" scoped>
/* Rename root class */
.universal-node-details {
  padding: 0 10px;
}

.section-margin {
  margin-top: 20px;
}

.value-display, .metadata-display, .content-display /* Added content-display */ {
  white-space: pre-wrap;
  word-break: break-all;
  font-family: monospace;
  font-size: 0.9em;
  background-color: var(--el-fill-color-lighter);
  padding: 5px;
  border-radius: 4px;
  margin: 0;
}

/* Keep tag styles */
:deep(.el-tag) {
  color: white;
  border-color: transparent;
}

.id-list {
  word-break: break-all;
}
</style>